<template>

  <el-cascader
    v-model="cascaderData"
    style="width: 230px"
    :show-all-levels="false"
    collapse-tags
    clearable
    :props="cascaderProps"
    @change="handleChange"
    :options="options"
    ref="cascaderRef"
    @expand-change="expandChange"
  />

</template>

<script>
import api from "@/api";
import {treeData,singleArr} from '@/util/index'
import { onMounted } from "vue";
export default defineComponent({
  props: {
    index: {
      type: Number,
      default: 0,
    },
    itemData: {
      type: Object,
      default: {},
    },
    value:{
      type:Array,
      default:()=>[]
    },
    path:{
      type:Array,
      default:()=>[]
    }
  },
  setup(props, context) {
    const cascaderData = ref(props.value);
    const options = ref([])

    const nodes = ref([])

    const cascaderRef = ref(null)

    const cascaderProps = ref({
      multiple: true,
      checkStrictly: true,
      emitPath: false,
      lazy: true,
      async lazyLoad(node, resolve) {
        const { level, value } = node;
        console.log(level, value)
        let data = [];
        if (level === 0) {
          data = await getDeptList();
        } else {
          data = await getDeptList({ parentId: value });
        }
        resolve(data);
      },
      value: "value",
    });
    const handleChange = () => {
      context.emit("handleChange", cascaderData, props.index, props.itemData,nodes.value);
    };
    const expandChange = (e)=>{
      nodes.value = e
    }
    const getDeptList = async (params = {}) => {
      const data = (await api.user.user_GetDept(params)) || [];
      return data;
    };
    onMounted(async ()=>{

      // 异步加载回显
      let curOptions = []
      let data = []
      if(Array.isArray(props.path) && props.path.length>0){
        data = await getDeptList();
        let num = 0
       curOptions.push(...data)
        props.path.forEach(async item => {
          data = await getDeptList({ parentId: item });
          ++num
         curOptions.push(...data)

         if (num==props.path.length) {
          options.value =treeData(curOptions,'value','parentId','0')
         }
        });





      }
    })
    return {
      cascaderData,
      cascaderProps,
      handleChange,
      cascaderRef,
      expandChange,
      options
    };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" >
</style>
